from flask_classy import FlaskView, route

from ..models.product import Product
from ..models.offer import Offer
from ..models.currency import Currency
from flask import request
from . import jsonify_with_success, jsonify_with_error
from ..schema.object import OfferSchema, ProductStockSchema


class StocksView(FlaskView):
    @route('/product/<product_id>')
    def fetch_product_stock(self, product_id):
        import copy
        currency_id = request.args.get('c', None)
        product = Product.get_or_none(Product.id == product_id)
        if not product: return jsonify_with_error(200001, '产品不存在')

        main_currency = Currency.get_main_currency()
        if not main_currency: return jsonify_with_error(9000001, '未设置主币种')

        if currency_id:
            currency = Currency.get_or_none(Currency.id == currency_id)
            if not currency: return jsonify_with_error(300001, '币种不存在')
        else:
            currency = main_currency

        stock_list = Offer.get_list(product)
        stock_list = sorted(stock_list, key=lambda s: s.price)

        recommend_stock = None
        for stock in stock_list:
            # stock.price = round(stock.price * currency.rate, 2)

            if stock.is_recommend():
                recommend_stock = copy.deepcopy(stock)

        if stock_list and not recommend_stock:
            recommend_stock = copy.deepcopy(stock_list[0])
        additional = []
        if recommend_stock:
            from ..models.service import Service
            from decimal import Decimal

            for s in ['TRS', ]:
                service = Service.get_or_none(Service.id == s)
                if not service: continue
                service_fee = Decimal.from_float(0.00)
                if service:
                    if service.mode == 'fixed':
                        service_fee = service.fee
                    elif service.mode == 'rate':
                        service_fee = recommend_stock.price * service.fee
                additional.append({
                    'name': s,
                    'amount': service_fee
                })

                # recommend_stock.price = round(recommend_stock.price + service_fee, 2)

        return jsonify_with_success(ProductStockSchema(
            context={'currency': currency}).dump({'currency': currency,
                                                  'stock': stock_list,
                                                  'recommend': {
                                                      'stock': recommend_stock,
                                                      'additional': additional
                                                  }}).data)
